import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @Author : lizhifeng
 * @create 2022/8/8 20:16
 * @DESC 2022/8/8 20:16
 */


public class Block {

    /**
     * 区块大小
     */
    private long blockSize;

    /**
     * 区块头
     */
    private Header header;

    private HashMap<TransactionId, Transaction> map = new HashMap<>();

    private List<TransactionId> transactionIdList;

    public long getBlockSize() {
        return blockSize;
    }

    public void setBlockSize(long blockSize) {
        this.blockSize = blockSize;
    }

    public int getHeight() {
        return header.getHeight();
    }

    public Block() {
    }

    public Block(Header header, List<TransactionId> transactionIdList) {
        this.header = header;
        this.transactionIdList = transactionIdList;
    }


    public synchronized void addTransaction(byte[] hash, Transaction transaction) {
        map.put(new TransactionId(hash), transaction);
    }

    public Header getHeader() {
        return header;
    }

    public void setHeader(Header header) {
        this.header = header;
    }

    public HashMap<TransactionId, Transaction> getMap() {
        return map;
    }

    public void setMap(HashMap<TransactionId, Transaction> map) {
        this.map = map;
    }


    public List<TransactionId> getTransactionIdList() {
        return transactionIdList;
    }

    public void setTransactionIdList(List<TransactionId> transactionIdList) {
        this.transactionIdList = transactionIdList;
    }

    public String getBlockListString() {

        byte[] merkleRoot = Miner.buildMerkleRoot(transactionIdList);

        StringBuilder sb = new StringBuilder();
        sb.append("transactionCount=" + transactionIdList.size());
        sb.append("\nmerkleRoot=");
        sb.append(Arrays.toString(merkleRoot));
        sb.append("\nlist={");

        int size = transactionIdList.size();
        int i = 1;

        for (TransactionId transactionId : transactionIdList) {
            sb.append(Arrays.toString(transactionId.getHash()));
            if (i < size) {
                sb.append(",\n");
            }
            i++;
        }

        sb.append("}");
        return sb.toString();
    }

}
